package com.x.xiaoshuo.ui.download;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.hwangjr.rxbus.RxBus;
import com.hwangjr.rxbus.annotation.Subscribe;
import com.hwangjr.rxbus.thread.EventThread;
import com.x.mvp.appbar.TransAppBarFragment;
import com.x.mvp.base.recycler.PullToRefreshRecyclerActivityView;
import com.x.mvp.base.recycler.RecyclerAdapter;
import com.x.mvp.base.recycler.RecyclerViewHolder;
import com.x.service.entity.BookListsBean;
import com.x.xiaoshuo.R;
import com.x.xiaoshuo.di.XActivityComponent;
import com.x.xiaoshuo.entity.DownloadMessage;
import com.x.xiaoshuo.entity.DownloadProgress;
import com.x.xiaoshuo.entity.DownloadQueue;
import com.x.xiaoshuo.service.DownloadBookService;
import com.x.xiaoshuo.ui.appbar.LeftTitleAppBarBuilder;
import com.x.xiaoshuo.ui.read.ReadActivity;
import com.x.xiaoshuo.widget.PrecentTextView;

import java.util.HashMap;
import java.util.List;

import in.srain.cube.views.ptr.PtrFrameLayout;


public class DownloadActivity extends PullToRefreshRecyclerActivityView<DownloadPresenter> {

    HashMap<String, DownloadQueue> downloadQueueHashMap = new HashMap<>();

    HashMap<String, DownloadProgress> downloadProgressHashMap = new HashMap<>();

    LeftTitleAppBarBuilder leftTitleAppBarBuilder;

    DownloadBookService service;

    private boolean isBind = false;

    private ServiceConnection conn = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder binder) {
            isBind = true;
            DownloadBookService.DownloadBinder myBinder = (DownloadBookService.DownloadBinder) binder;
            service = myBinder.getService();
            List<DownloadQueue> queues = service.getDownloadQueues();
            for (DownloadQueue queue : queues) {
                downloadQueueHashMap.put(queue.bookId, queue);
            }
            showData(queues);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            isBind = false;
        }
    };

    public static void startActivity(Context context) {
        context.startActivity(new Intent(context, DownloadActivity.class));
    }

    @Override
    protected void injectComponent() {
        ((XActivityComponent) getActivityComponent()).inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_lst;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected int getPullMode() {
        return PULL_MODE_DISABLED;
    }

    @Override
    protected void initView() {
        super.initView();
        leftTitleAppBarBuilder = new LeftTitleAppBarBuilder();
        TransAppBarFragment appBarFragment = leftTitleAppBarBuilder.setOnRightClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        }).setOnLeftClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        }).builder();
        leftTitleAppBarBuilder.setRes(R.drawable.ic_back_gray);
        leftTitleAppBarBuilder.setText("下载管理");
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.appbar_container, appBarFragment)
                .commitAllowingStateLoss();
        bindDownloadService();
        RxBus.get().register(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxBus.get().unregister(this);
    }


    @Subscribe(thread = EventThread.MAIN_THREAD)
    public synchronized void eDownloadMessage(DownloadMessage queue) {
        if (!TextUtils.isEmpty(queue.bookId)) {

        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public synchronized void eDownloadMessage(DownloadProgress queue) {
        if (!TextUtils.isEmpty(queue.bookId)) {
            downloadProgressHashMap.put(queue.bookId, queue);
            getAdapter().notifyDataSetChanged();
        }
    }

    @Subscribe(thread = EventThread.MAIN_THREAD)
    public synchronized void eDownloadMessage(DownloadQueue queue) {
        if (!TextUtils.isEmpty(queue.bookId)) {
            downloadQueueHashMap.put(queue.bookId, queue);
            getAdapter().notifyDataSetChanged();
        }
    }


    void bindDownloadService() {
        Intent intent = new Intent(this, DownloadBookService.class);
        this.getApplicationContext().bindService(intent, conn, BIND_AUTO_CREATE);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {

    }

    @Override
    protected RecyclerView.LayoutManager getLayoutManager() {
        return new LinearLayoutManager(this);
    }

    DownloadAdapter downloadAdapter;

    void showData(List<DownloadQueue> queues) {
        if (queues != null) {
            getAdapter().replaceAll(queues);
        }
    }

    @Override
    protected RecyclerAdapter getAdapter() {
        if (downloadAdapter == null) {
            downloadAdapter = new DownloadAdapter(getRecyclerView());
            downloadAdapter.setOnItemClickListener(new RecyclerAdapter.OnItemClickListener<DownloadQueue>() {
                @Override
                public void onItemClick(View view, DownloadQueue data, int position) {
                    BookListsBean bookListsBean = new BookListsBean();
                    bookListsBean._id = data.bookId;
                    bookListsBean.title = data.title;
                    ReadActivity.startActivity(DownloadActivity.this, bookListsBean);
                    DownloadActivity.this.finish();
                }
            });
        }
        return downloadAdapter;
    }

    class DownloadHolder extends RecyclerViewHolder<DownloadQueue> {
        PrecentTextView precentage;
        TextView title;
        TextView propress;

        public DownloadHolder(View itemView) {
            super(itemView);
            propress = itemView.findViewById(R.id.propress);
            title = itemView.findViewById(R.id.title);
            precentage = itemView.findViewById(R.id.precentage);
        }

        @Override
        public void bindView(DownloadQueue data) {
            title.setText(data.title);
            DownloadProgress downloadProgress = downloadProgressHashMap.get(data.bookId);
            if (downloadProgress != null) {
                propress.setText("正在下载 " + downloadProgress.chapter + "/" + downloadProgress.chapterSize + "章");
                float download = downloadProgress.chapter - data.start;
                float all = data.end - data.start;
                float p = ((download / all));
                if (download == all) {
                    propress.setText("下载完成 ");
                }
                precentage.setContentValue(new float[]{p, 0});
            } else {
                precentage.setContentValue(new float[]{0, 0});
                propress.setText("等待下载");
            }

            if (data.isCancel) {
                propress.setText("暂停下载");
            }

            precentage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (!data.isFinish) {
                        data.isCancel = !data.isCancel;
                        if (!data.isCancel) {
                            propress.setText("等待下载");
                        } else {
                            propress.setText("暂停下载");
                        }
                        service.changeDownLoad(data);
                    }
                }
            });
        }
    }

    class DownloadAdapter extends RecyclerAdapter<DownloadQueue, DownloadHolder> {

        public DownloadAdapter(RecyclerView recyclerView) {
            super(recyclerView);
        }

        @Override
        protected int getItemLayoutID(int viewType) {
            return R.layout.item_download;
        }

        @Override
        protected DownloadHolder createItemViewHolder(View itemView, int viewType) {
            return new DownloadHolder(itemView);
        }

        @Override
        protected int getViewType(int position) {
            return 0;
        }

        @Override
        protected void onBindItemViewHolder(DownloadHolder holder, int position, int index, boolean isScrolling) {
            holder.bindView(getData().get(position));
        }
    }
}
